<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            border:1px solid red;
        }
    </style>
</head>
<body>
    图片名  <input type="text" name="" id="name"><br>
    图片    <input type="file" name="" id="img"><br>
    <button>点击传图ajax</button>
    <div class="box"></div>
    <script>
        let nameEle = document.querySelector("#name");
        let imgEle = document.querySelector("#img");
        let btn = document.querySelector("button");
        let boxEle = document.querySelector(".box");
        btn.onclick = function (){
            let name = nameEle.value;
            let imgFile = imgEle.files[0];      //获取文件对象
            let form = new FormData();
            form.append("name",name);
            form.append("img",imgFile);
            let xhr = new XMLHttpRequest();
            xhr.open("POST","file.php",true);
            xhr.onload = function (){
                // console.log(xhr.responseText);
                let data = JSON.parse(xhr.responseText);
                boxEle.style.background = `url(./images/${data['img']})`;
            }
            xhr.send(form);
        }
    </script>
</body>
</html>